package top.ajunnihao.core.task.tasks;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.ajunnihao.core.entity.Message;
import top.ajunnihao.core.mapper.MessageMapper;
import top.ajunnihao.core.task.Task;
import top.ajunnihao.core.web.controller.MessageController;

import java.io.File;
import java.util.List;

/**
 * TODO 帖子删除定时任务
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/5/31
 */
@Component
public class MsgDelTask implements Task {

    /**
     * 记录日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MsgDelTask.class);

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public void execute() {
        LOGGER.info("** 清理message表中待删除帖子(delFlag=1) => Start");
        // 查询 delFlag=1 的帖子
        List<Message> messages = messageMapper.findDelMsg();
        for (Message message : messages) {
            // 清理帖子及附件文件
            cleanMsg(message);
        }
    }

    /**
     * 清理待删除帖子
     */
    public void cleanMsg(Message message) {
        // 删除附件照片目录及文件
        File storeDir = MessageController.store.getFile(message.getStorePath());
        if (storeDir.exists()) {
            try {
                // 删除文件
                FileUtils.deleteQuietly(storeDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 删除数据库记录
        messageMapper.deleteMessage(message.getId());
    }

}
